<?php

class Uploadmodel extends Model
{
	function Uploadmodel() 
	{
		//Constructor
		parent::Model();
		$this->load->helper('date');
		
	}
	
	function upload_photo($userId)
	{
		$photo_path = realpath(APPPATH . 'userdata/profile_' . $userId . '/photos/');
		$config = array(
							'upload_path' => $photo_path,
							'allowed_types' => 'jpg|jpeg',
							'max_size' => '4096'
						);
		$this->load->library('upload', $config);
		$upload = $this->upload->do_upload();
		$image_data = $this->upload->data();
		//Create Thumbs
		$config = array(
			'source_image' => $image_data['full_path'],
			'new_image' => $photo_path . '/thumbs/',
			'maintain_ration' => true,
			'width' => 80,
			'height' => 80
		);
		
		$this->load->library('image_lib', $config);
		$this->image_lib->resize();
		//end upload
		
		if($upload == false)
		{
			if($this->upload->display_errors());
			{
				$this->session->set_flashdata('error',  '<b>เกิดข้อผิดพลาด! อาจเกิดจากสาเหตุดังนี้</b> <br /> 1.ไฟล์ภาพมีขนาดใหญ่เกินไป(ไม่เกิน 4MB) <br />  2.เป็นไฟล์ที่ไม่ถูกประเภท(สนับสนุน .jpg .jpeg เท่านั้น) <br />  3.คุณยังไม่ได้เลือกภาพถ่ายใดๆเลย');
				redirect('profile/upload');
			}
		}
		else
		{	
		//Get EXIF Data
			
			$filename = $image_data['full_path'];
			
			// function คำนวนหา GPS Data //
			function ConvertFractionToDecimal($fraction)
			{
			    $result = "";
			    if (isset($fraction))
			    {
				eval ("\$result = 1.0*$fraction;");
			    }
			    return $result;
			}
			
			function ExifConvertDegMinSecToDD($deg, $min, $sec)
			{
			    $dec_min = ($min*60.0 + $sec)/60.0;
			    $result  = ($deg*60.0 + $dec_min)/60.0;
			    return $result;
			}
			
			$exif_data = array();
			$rawexif = exif_read_data($filename, 0, true);
			
			if (isset($rawexif['GPS']))
			{
				$deg = ConvertFractionToDecimal($rawexif['GPS']['GPSLatitude'][0]);
				$min = ConvertFractionToDecimal($rawexif['GPS']['GPSLatitude'][1]);
				$sec = ConvertFractionToDecimal($rawexif['GPS']['GPSLatitude'][2]);
				$exif_data['GPSLatitude'] = ExifConvertDegMinSecToDD($deg, $min, $sec);
				$exif_data['GPSLatitudeRef'] = $rawexif['GPS']['GPSLatitudeRef'];
			    
				$deg = ConvertFractionToDecimal($rawexif['GPS']['GPSLongitude'][0]);
				$min = ConvertFractionToDecimal($rawexif['GPS']['GPSLongitude'][1]);
				$sec = ConvertFractionToDecimal($rawexif['GPS']['GPSLongitude'][2]);
				$exif_data['GPSLongitude'] = ExifConvertDegMinSecToDD($deg, $min, $sec);
				$exif_data['GPSLongitudeRef'] = $rawexif['GPS']['GPSLongitudeRef'];
				    
				$Lat = $exif_data['GPSLatitude'];
				$Lng = $exif_data['GPSLongitude'];
				
				//echo $Lat . '/' . $Lng;
			}
			
			$datetime = date('Y-m-d H:i:s');
			$location = $this->input->post('photo_name');
			$description = $this->input->post('photo_desc');
			$status = $this->input->post('photo_status');
			$type = $this->input->post('type');
			$this->db->set('user_id', $userId);
			$this->db->set('caption', $image_data['file_name']);
			$this->db->set('photo_status', $status);
			$this->db->set('location', $location);
			$this->db->set('detail', $description);
			$this->db->set('type', $type);
			@$this->db->set('latitude', $Lat); //ปิด error หากภาพไม่มี GPS
			@$this->db->set('longitude', $Lng); //ปิด error หากภาพไม่มี GPS
			$this->db->set('datetime', $datetime);
			$this->db->insert('photos');
			
			//$action = 2;
			//$am = $this->usermodel->getName($this->session->userdata('userId'));
			//$data = "<img src='".base_url()."application/images/picture1.gif' /><i>" . $am . " ทำการอัพโหลดภาพถ่ายบนโปรไฟล์ </i>";
			//$this->wallmodel->wallPost($this->session->userdata('userId'), $this->session->userdata('userId'), $data, $action);
			
			//FB Post

# We require the library
require("application/external/facebook.php");

# Creating the facebook object
$facebook = new Facebook(array(
	'appId'  => '23567002744',
	'secret' => 'eb005a40ebf5dde3b53488fce98817da',
	'cookie' => true
));

# Let's see if we have an active session
$session = $facebook->getSession();

if(!empty($session)) {
	# Active session, let's try getting the user id (getUser()) and user info (api->('/me'))
	try{
		$uid = $facebook->getUser();
		
		# let's check if the user has granted access to posting in the wall
		$api_call = array(
			'method' => 'users.hasAppPermission',
			'uid' => $uid,
			'ext_perm' => 'publish_stream'
		);
		$can_post = $facebook->api($api_call);
		if($can_post){
			# post it!
			# $facebook->api('/'.$uid.'/feed', 'post', array('message' => 'Saying hello from my Facebook app!'));
			
			# using all the arguments
			$facebook->api('/'.$uid.'/feed', 'post', array(
				'message' => $location,
				'name' => 'Panoramap.in.th',
				'description' => $description,
				'caption' => 'Location Based Social Networking',
				'picture' => 'http://www.panoramap.in.th/application/userdata/profile_31/photos/IMG00126-20100623-1328.jpg',
				'link' => 'http://www.panoramap.in.th/photo/id/169/'
			));
			//echo 'Posted!';
		} else {
			die('Permissions required!');
		}
	} catch (Exception $e){}
} else {
	# There's no active session, let's generate one
	$login_url = $facebook->getLoginUrl();
	header("Location: ".$login_url);
}




			$this->session->set_flashdata('success',  'อัพโหลดภาพถ่ายของคุณเรียบร้อยแล้ว คุณสามารถอัพโหลดภาพถ่ายอื่นๆของคุณได้ที่ <a href="upload">อัพโหลด</a>');
			redirect('profile/album');
		}
	}



	
}
